<template>
  <div class="login-form-body">
    <div class="header">
      <div v-show="type === LoginType.User"
           @click="type = LoginType.MsgCode">
        <i class="iconfont icon-msg"/>
        使用短信登录
      </div>
      <div v-show="type === LoginType.MsgCode"
           @click="type = LoginType.User">
        <i class="iconfont icon-user"/>
        使用账号登录
      </div>
    </div>
    <div class="body">
      <!-- 账号登录 -->
      <template v-if="type === LoginType.User">
        <login-input ref="userInput"
                     v-model="user"
                     :rules="formRule.username"
                     icon="user"
                     placeholder="请输入用户名"/>
        <login-input ref="pwdInput"
                     v-model="pwd"
                     :rules="formRule.password"
                     icon="lock"
                     placeholder="请输入密码"
                     type="password"/>
      </template>

      <!-- 短信登录 -->
      <template v-else-if="type === LoginType.MsgCode">
        <login-input ref="mobileInput"
                     v-model="mobile"
                     :rules="formRule.mobile"
                     icon="user"
                     placeholder="请输入手机号"/>
        <login-input ref="codeInput"
                     v-model="code"
                     :rules="formRule.code"
                     icon="user"
                     placeholder="请输入验证码">
          <div :class="{disable: time}"
               class="code"
               @click="sendCodeClick">
            {{ time ? `${time}秒后重试` : '发送验证码' }}
          </div>
        </login-input>
      </template>

      <!-- 免责条款 -->
      <div class="agree">
        <checkbox v-model="agree"
                  class="checkbox"/>
        我已同意
        <router-link to="">《隐私条款》</router-link>
        和
        <router-link to="">《服务条款》</router-link>
      </div>
      <div class="err-msg">
        <div v-show="!agree">
          <i class="iconfont icon-warning"/>
          请勾选登录协议
        </div>
      </div>

      <!-- 登录按钮 -->
      <div class="login"
           @click="login">
        登录
      </div>
    </div>
    <div class="footer">
      <!-- QQ登录 -->
      <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"/>
      </a>

      <!-- 其它 -->
      <div class="option">
        <router-link to="">忘记密码</router-link>
        <router-link to="">免费注册</router-link>
      </div>
    </div>
  </div>
</template>

<script lang="ts"
        setup>
import {msgLogin, sendCode, userLogin} from '@/api/login'
import {formRule} from '@/assets/utils/validate'
import Checkbox from '@/components/library/Checkbox.vue'
import LoginInput from '@/components/library/XtxInput.vue'
import message from '@/components/library/Message/index'
import {useCartStore} from '@/stores/cart'
import {useUserStore} from '@/stores/user'
import {LoginType} from '@/types/login'
import type {UserInfo} from '@/types/user'

import {onBeforeUnmount, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'


let router = useRouter()
let route = useRoute()

let type = ref<LoginType>(LoginType.User)

let user = ref<string>('hwt1632810172')
let pwd = ref<string>('123456')
let mobile = ref<string>('18106001915')
let code = ref<string>('123456')

let userInput = ref()
let pwdInput = ref()
let mobileInput = ref()
let codeInput = ref()

let agree = ref<boolean>(true)

async function login() {
  if (!agree.value) return

  let judge: any[] = []
  let params: string[] = []
  let loginApi: Function = () => ({message: '未知的登录方式'})
  if (type.value === LoginType.User) {
    judge = [userInput.value, pwdInput.value]
    params = [user.value, pwd.value]
    loginApi = userLogin
  } else if (type.value === LoginType.MsgCode) {
    judge = [mobileInput.value, codeInput.value]
    params = [mobile.value, code.value]
    loginApi = msgLogin
  }

  let judgeKey: boolean = true
  for (let item of judge)
    if (!item.judge())
      judgeKey = false
  if (!judgeKey) return

  let res: any = await loginApi(...params)
  if (res.message) return message.error(res.message)
  message.success('登录成功')
  // 保存登录信息
  useUserStore().userInfo = <UserInfo>res.result
  // 初始化购物车
  await useCartStore().initCart()
  await router.push(<string | undefined>route?.query?.redirect ?? '/')
}


let time = ref<number>(0)
let timer: number | undefined = undefined

onBeforeUnmount(() => {
  clearInterval(timer)
})

function initInterval() {
  time.value = 60
  clearInterval(timer)
  timer = setInterval(() => {
    time.value--
    if (time.value <= 0) {
      time.value = 0
      clearInterval(timer)
    }
  }, 1000)
}

async function sendCodeClick() {
  if (!mobileInput.value.judge() || time.value !== 0) return
  let res: any = await sendCode(mobile.value)
  if (res.message) return message.error(res.message)
  message.success('发送成功')
  initInterval()
}
</script>

<style lang="less"
       scoped>
.login-form-body {
  padding: 0 40px;

  .header {
    height: 50px;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    div {
      color: @xtxColor;
      cursor: pointer;

      i {
        font-size: 14px;
      }
    }
  }

  .body {
    .agree {
      display: flex;
      align-items: center;

      .checkbox {
        margin-top: 2px;
        margin-right: 5px;
      }

      a {
        color: #069;
      }
    }

    .err-msg {
      height: 28px;
      line-height: 28px;
      font-size: 12px;
      color: @priceColor;

      i {
        font-size: 14px;
      }
    }

    .code {
      width: 90px;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #f5f5f5;
      color: #666666;
      border-left: 1px solid #cfcdcd;
      cursor: pointer;

      &.disable {
        cursor: not-allowed;
      }
    }

    .login {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: @xtxColor;
      color: white;
      cursor: pointer;
    }
  }

  .footer {
    padding: 20px 0;
    display: flex;
    justify-content: space-between;

    .option {
      a {
        margin-left: 10px;
        color: #999999;
      }
    }
  }
}
</style>